/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2024-11-22 20:44:03
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-11-23 21:40:21
 * @FilePath: \vue-admin\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { getToken } from './auth'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    Message.error(error.response.data.msg)
    console.dir(error.response.statue)
    if (error.response.status === 401) {
      // 跳转到登录
      router.push('./login')
      // 清空用户数据
      store.commit('user/clearUserInfo')
    }
    return Promise.reject(error)
  }
)

export default service
